<template>
  <div class="player-container">
    <div class="video-wrapper" @mousemove="showControls" @mouseleave="hideControls">
      <!-- 视频加载状态 -->
      <div class="loading-overlay" v-if="loading">
        <div class="spinner"></div>
        <p>正在加载视频资源...</p>
      </div>

      <!-- 错误状态 -->
      <div class="error-overlay" v-if="error">
        <i class="fas fa-exclamation-triangle" style="font-size: 3rem; margin-bottom: 20px"></i>
        <p class="error-message">视频加载失败: {{ errorMessage }}</p>
        <button class="retry-btn" @click="loadVideo">重试</button>
      </div>

      <!-- 视频元素 -->
      <video
        ref="videoPlayer"
        @timeupdate="updateProgress"
        @loadedmetadata="onVideoLoaded"
        @canplay="onCanPlay"
        @waiting="onWaiting"
        @error="onVideoError"
        @click="togglePlay"
      ></video>

      <!-- 自定义控制条 -->
      <div class="controls" :class="{ hidden: !showControlBar }">
        <div class="progress-container" @click="setProgress">
          <div class="progress-bar" :style="{ width: progressPercentage + '%' }"></div>
        </div>

        <div class="control-buttons">
          <div class="left-controls">
            <button class="control-btn" @click="togglePlay">
              <i class="fas" :class="isPlaying ? 'fa-pause' : 'fa-play'"></i>
            </button>
            <div class="volume-container">
              <button class="control-btn" @click="toggleMute">
                <i class="fas" :class="isMuted ? 'fa-volume-mute' : 'fa-volume-up'"></i>
              </button>
              <input
                type="range"
                class="volume-slider"
                min="0"
                max="1"
                step="0.01"
                v-model="volume"
              />
            </div>
            <div class="time-display">
              {{ formatTime(currentTime) }} / {{ formatTime(duration) }}
            </div>
          </div>

          <div class="right-controls">
            <button class="control-btn" @click="toggleFullscreen">
              <i class="fas fa-expand fullscreen-icon"></i>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, reactive, watch } from 'vue';

  const props = defineProps({
    chapterRow: {
      type: Object,
      default: () => null,
    },
  });

  // 视频播放器引用
  const videoPlayer = ref<any>(null);

  // 播放器状态
  const isPlaying = ref(false);
  const isMuted = ref(false);
  const currentTime = ref(0);
  const duration = ref(0);
  const progressPercentage = ref(0);
  const volume = ref(0.7);
  const showControlBar = ref(true);
  const loading = ref(true);
  const error = ref(false);
  const errorMessage = ref('');
  const currentVideo = ref(0);

  // 控制条自动隐藏定时器
  let controlTimeout;

  // 视频列表（模拟API返回的数据）
  const videoList = reactive([
    {
      id: 1,
      title: '自然风光',
      description: '高清自然风光纪录片',
      url: 'https://vjs.zencdn.net/v/oceans.mp4',
    },
    {
      id: 2,
      title: '城市夜景',
      description: '4K超清城市夜景延时摄影',
      url: 'https://assets.codepen.io/3364143/sample.mp4',
    },
    {
      id: 3,
      title: '科技展示',
      description: '未来科技概念展示',
      url: 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4',
    },
  ]);

  // 初始化播放器
  const initPlayer = () => {
    if (videoPlayer.value) {
      videoPlayer.value.volume = volume.value;
      videoPlayer.value.muted = isMuted.value;
    }
  };

  // 播放/暂停切换
  const togglePlay = () => {
    if (!videoPlayer.value) return;

    if (videoPlayer.value.paused) {
      videoPlayer.value
        .play()
        .then(() => {
          isPlaying.value = true;
        })
        .catch((e) => {
          error.value = true;
          errorMessage.value = '播放失败: ' + e.message;
        });
    } else {
      videoPlayer.value.pause();
      isPlaying.value = false;
    }

    showControls();
  };

  // 静音切换
  const toggleMute = () => {
    isMuted.value = !isMuted.value;
    if (videoPlayer.value) {
      videoPlayer.value.muted = isMuted.value;
    }
  };

  // 更新播放进度
  const updateProgress = () => {
    if (!videoPlayer.value) return;

    currentTime.value = videoPlayer.value.currentTime;
    duration.value = videoPlayer.value.duration;

    if (duration.value > 0) {
      progressPercentage.value = (currentTime.value / duration.value) * 100;
    }
  };

  // 设置播放进度
  const setProgress = (e) => {
    if (!videoPlayer.value) return;

    const progressContainer = e.currentTarget;
    const clickPosition =
      (e.pageX - progressContainer.getBoundingClientRect().left) / progressContainer.offsetWidth;
    videoPlayer.value.currentTime = clickPosition * duration.value;
  };

  // 格式化时间 (秒 -> mm:ss)
  const formatTime = (time) => {
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  };

  // 切换全屏
  const toggleFullscreen = () => {
    if (!videoPlayer.value) return;

    if (!document.fullscreenElement) {
      if (videoPlayer.value.requestFullscreen) {
        videoPlayer.value.requestFullscreen();
      } else if (videoPlayer.value.mozRequestFullScreen) {
        videoPlayer.value.mozRequestFullScreen();
      } else if (videoPlayer.value.webkitRequestFullscreen) {
        videoPlayer.value.webkitRequestFullscreen();
      } else if (videoPlayer.value.msRequestFullscreen) {
        videoPlayer.value.msRequestFullscreen();
      }
    } else {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      }
    }
  };

  // 显示控制条
  const showControls = () => {
    showControlBar.value = true;
    clearTimeout(controlTimeout);
    controlTimeout = setTimeout(() => {
      if (isPlaying.value) {
        showControlBar.value = false;
      }
    }, 3000);
  };

  // 隐藏控制条
  const hideControls = () => {
    if (isPlaying.value) {
      controlTimeout = setTimeout(() => {
        showControlBar.value = false;
      }, 1000);
    }
  };

  // 视频加载完成
  const onVideoLoaded = () => {
    duration.value = videoPlayer.value.duration;
    loading.value = false;
    error.value = false;
    isPlaying.value = true;
    showControls();
  };

  // 视频可以播放
  const onCanPlay = () => {
    loading.value = false;
    error.value = false;
  };

  // 视频加载中
  const onWaiting = () => {
    loading.value = true;
  };

  // 视频加载错误
  const onVideoError = () => {
    if (videoPlayer.value) {
      error.value = true;
      errorMessage.value = '无法加载视频资源';
      loading.value = false;
    }
  };

  // 加载视频
  const loadVideo = () => {
    loading.value = true;
    error.value = false;

    // 模拟API请求延迟
    setTimeout(() => {
      if (videoPlayer.value) {
        videoPlayer.value.src = props.chapterRow.videoUrl;
        videoPlayer.value.load();
        videoPlayer.value.play();
      }
    }, 800);
  };

  // 监听音量变化
  watch(volume, (newVal) => {
    if (videoPlayer.value) {
      videoPlayer.value.volume = newVal;
      isMuted.value = newVal === 0;
    }
  });

  // 初始化
  onMounted(() => {
    initPlayer();
    loadVideo();
    showControls();
  });
</script>

<style lang="less" scoped>
  header {
    text-align: center;
    margin-bottom: 30px;
    color: white;
  }

  h1 {
    font-size: 2.8rem;
    margin-bottom: 10px;
    text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  }

  .subtitle {
    font-size: 1.2rem;
    opacity: 0.9;
  }

  .player-container {
    border-radius: 16px;
    overflow: hidden;
    position: relative;
    margin: 0 auto;
  }

  .video-wrapper {
    //position: relative;
    padding-top: 56.25%; /* 16:9 Aspect Ratio */
    background: #000;
  }

  video {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    outline: none;
    background: #000;
  }

  .controls {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);
    padding: 20px 15px 10px;
    display: flex;
    flex-direction: column;
    transition: opacity 0.3s;
  }

  .controls.hidden {
    opacity: 0;
    pointer-events: none;
  }

  .progress-container {
    width: 100%;
    height: 6px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 3px;
    margin-bottom: 15px;
    cursor: pointer;
    position: relative;
  }

  .progress-bar {
    height: 100%;
    background: #ff4757;
    border-radius: 3px;
    width: 0%;
    position: relative;
  }

  .progress-bar::after {
    content: '';
    position: absolute;
    right: -8px;
    top: 50%;
    transform: translateY(-50%);
    width: 16px;
    height: 16px;
    background: #fff;
    border-radius: 50%;
    opacity: 0;
    transition: opacity 0.2s;
  }

  .progress-container:hover .progress-bar::after {
    opacity: 1;
  }

  .control-buttons {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .left-controls,
  .right-controls {
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .control-btn {
    background: transparent;
    border: none;
    color: white;
    font-size: 1.2rem;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    height: 36px;
    transition: all 0.2s;
    border-radius: 50%;
  }

  .control-btn:hover {
    background: rgba(255, 255, 255, 0.1);
    transform: scale(1.1);
  }

  .control-btn:active {
    transform: scale(0.95);
  }

  .volume-container {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .volume-slider {
    width: 80px;
    -webkit-appearance: none;
    height: 5px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 5px;
    outline: none;
  }

  .volume-slider::-webkit-slider-thumb {
    -webkit-appearance: none;
    width: 14px;
    height: 14px;
    border-radius: 50%;
    background: white;
    cursor: pointer;
  }

  .time-display {
    color: white;
    font-size: 0.9rem;
    min-width: 100px;
  }

  .loading-overlay,
  .error-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: white;
    z-index: 10;
  }

  .spinner {
    width: 50px;
    height: 50px;
    border: 5px solid rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    border-top: 5px solid #ff4757;
    animation: spin 1s linear infinite;
    margin-bottom: 20px;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }

  .error-message {
    text-align: center;
    padding: 20px;
    color: #ff6b6b;
    font-size: 1.1rem;
  }

  .retry-btn {
    background: #ff4757;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 50px;
    margin-top: 15px;
    cursor: pointer;
    font-weight: bold;
    transition: all 0.3s;
  }

  .retry-btn:hover {
    background: #ff6b81;
    transform: translateY(-2px);
  }

  .fullscreen-btn .fullscreen-icon,
  video:fullscreen .fullscreen-btn .fullscreen-icon {
    display: none;
  }

  video:fullscreen .fullscreen-btn .exit-fullscreen-icon {
    display: block;
  }

  .fullscreen-btn .exit-fullscreen-icon {
    display: none;
  }

  @media (max-width: 768px) {
    .volume-slider {
      width: 60px;
    }

    .time-display {
      min-width: 80px;
      font-size: 0.8rem;
    }
  }
</style>
